<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/11/24
 * Time: 17:18
 */

namespace app\common\lib;


use app\exception\IndexException;

class YidunQuickPass
{
    protected $secretId = 'ed3d5d5684c02d65ce35644b52f1a5ea';
    protected $secretKey = '32630989d6d578531e53f2d9cbbc770d';
    protected $businessId = 'd16a733cc80e4f59968a98ff7ad0b41b';

    protected static $instance;

    public function __construct()
    {
    }

    public static function getInstance()
    {
//        if (is_object(self::$instance)) {
//            return self::$instance;
//        }

        return new self();
    }

    /**
     * 计算参数签名
     * @param $params
     * @return string
     */
    protected function genSignature($params)
    {
        $secretKey = $this->secretKey;
        ksort($params);
        $buff = "";
        foreach ($params as $key => $value) {
            if ($value !== null) {
                $buff .= $key;
                $buff .= $value;
            }
        }
        $buff .= $secretKey;
        return md5(mb_convert_encoding($buff, "utf8", "auto"));
    }

    /**
     * 将输入数据的编码统一转换成utf8
     * @params 输入的参数
     */
    protected function toUtf8($params)
    {
        $utf8s = array();
        foreach ($params as $key => $value) {
            $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", "auto") : $value;
        }
        return $utf8s;
    }

    public function oneKeyLogin($param)
    {
        $apiParam = [
            'secretId'=>$this->secretId,
            'businessId'=>$this->businessId,
            'version'=>'v1',
            'timestamp'=>(int)sprintf("%d", round(microtime(true) * 1000)),
            'nonce'=>substr(md5(time()), 0, 32),

            'accessToken'=>$param['accessToken'],
            'token'=>$param['token'],
        ];
        $apiParam = $this->toUtf8($apiParam);
        $apiParam["signature"] = $this->genSignature($apiParam);

        $headers = [
            'Content-Type'=>'application/x-www-form-urlencoded'
        ];
        $result = Guzzle::post('https://ye.dun.163yun.com/','v1/oneclick/check',$apiParam,$headers,'fromData');

        if(!empty($result['data']['phone']) && Common::checkMobile($result['data']['phone'])){
            return $result['data']['phone'];
        }else{
            throw new IndexException(4020,'手机号获取失败');
        }
    }
}